cc.Class({
    extends: cc.Component,

    properties: {
        editBox: cc.EditBox,
    },


    onEnable() {
        this.lobbyMain = cc.find("Canvas").getComponent("lobbyMain");
        this.playerInfo = this.lobbyMain.playerInfo;
        this.lobbyNet = this.lobbyMain.lobbyNet;
    },

    start() {
        this.pasteButton = this.node.getChildByName("btn_g");

        //粘贴
        this.pasteButton.on('click', async (event) => {
            if (cc.sys.isNative) {
                this.onPasteClickedByAndroid();
            } else {
                if (navigator.clipboard && navigator.clipboard.readText) {
                    try {
                        let text = await navigator.clipboard.readText();
                        this.editBox.string = text;
                    } catch (err) {
                        console.error('读取剪贴板失败:', err);
                    }
                } else if (event.clipboardData && event.clipboardData.getData) {
                    // 兼容旧方案：从粘贴事件中读取
                    let text = event.clipboardData.getData('text');
                    this.editBox.string = text;
                } else {
                    console.warn('当前环境不支持navigator.clipboard.readText');
                    // 你可以提示用户，或者做其他降级处理
                }
            }
        });
    },

    onClick(event, target) {
        this.lobbyMain.playClickSound();
        if (target == "bind") {    //绑定
            this.goBindAgent();
        }
    },

    //绑定代理返回
    onBindAgentResult(data) {
        this.lobbyMain.loading.active = false;
        if (data.respCode == "SUCCESS") {
            this.lobbyMain.showTips(data.message);
            this.lobbyMain.hidePanel(this.node);

            if (data.type == "agentId") {
                this.playerInfo.agentId = data.info;
            } else if (data.type == "inviterId") {
                this.playerInfo.inviterId = data.info;
            }
        } else {
            this.lobbyMain.showTips(data.message);
        }
    },

    // 发送绑定事件
    goBindAgent() {
        this.lobbyMain.openLoading();
        let str = this.editBox.string;
        if (str == "") {
            this.lobbyMain.showTips("Please enter your agent ID or the link your friend sent you.");
            this.lobbyMain.loading.active = false;
            return;
        }

        let info = this.parseInfo(str);
        if (!info) {
            this.lobbyMain.showTips("Please enter your agent ID or the link your friend sent you.");
            this.lobbyMain.loading.active = false;
            return;
        }
        let type = info.type;
        if (type == "inviterId") {
            str = info.value
        }

        let data = {
            action: "bindAgent",
            type: type,
            info: str,
            playerId: this.playerInfo.playerId,
        };
        this.lobbyNet.sendMessage(data)
    },


    //分析填入的值
    parseInfo(info) {
        if (info == null) return null;

        const str = String(info).trim();

        // 1. 判断是否是整数 => agentId
        if (/^-?\d+$/.test(str)) {
            return { type: "agentId", value: parseInt(str, 10) };
        }

        // 2. 尝试当作 URL 解析 => inviterId
        try {
            let urlStr = str;

            if (!/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(urlStr)) {
                urlStr = "http://" + urlStr;
            }

            const url = new URL(urlStr);
            const inviterId = url.searchParams.get("inviterId");

            if (inviterId == null) return null;

            const value = /^-?\d+$/.test(inviterId) ? parseInt(inviterId, 10) : inviterId;
            return { type: "inviterId", value };
        } catch (e) {
            return null;
        }
    },

    onPasteClickedByAndroid(event) {
        if (cc.sys.os === cc.sys.OS_ANDROID) {
            let pasteContent = jsb.reflection.callStaticMethod(
                "org/cocos2dx/javascript/AppActivity",
                "getClipboardContent",
                "()Ljava/lang/String;"
            );
            this.editBox.string = pasteContent;
        } else if (cc.sys.os === cc.sys.OS_IOS) {
            console.log("iOS 原生环境，需调用原生接口获取剪贴板");
        }
    },

    // update (dt) {},
});
